package com.fangs.yehwangglobal.net;


import com.fangs.yehwangglobal.BuildConfig;
import com.fangs.yehwangglobal.base.YehApp;
import com.fangs.yehwangglobal.utils.LogUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by Cicinnus on 2017/3/29.
 */
public class OkHttpManager {

    private static OkHttpClient okHttpClient;

    public static OkHttpClient getInstance() {
        // 指定缓存路径,缓存大小 50Mb
        Cache cache = new Cache(new File(YehApp.getInstance().getCacheDir(), "HttpCache"),
                1024 * 1024 * 50);
        if (okHttpClient == null) {
            synchronized (OkHttpManager.class) {
                if (okHttpClient == null) {
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    if (BuildConfig.DEBUG) {
                        builder.addInterceptor(httpLoggingInterceptor);
                    }
                    //超时时间
                    builder.connectTimeout(5, TimeUnit.SECONDS);//15S连接超时
                    builder.readTimeout(10, TimeUnit.SECONDS);//20s读取超时
                    builder.writeTimeout(10, TimeUnit.SECONDS);//20s写入超时
//                    builder.addInterceptor(headerInterceptor);//请求头
                    builder.addInterceptor(mUrlInterceptor);//url重定向
                    builder.cache(cache);//设置缓存
                    builder.addNetworkInterceptor(cacheInterceptor);
                    builder.addInterceptor(cacheControlInterceptor);
                    //错误重连
                    builder.retryOnConnectionFailure(true);
                    okHttpClient = builder.build();
                }
            }
        }
        return okHttpClient;
    }

    private static final HttpLoggingInterceptor httpLoggingInterceptor =
            new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                private final StringBuilder mMessage = new StringBuilder();

                @Override
                public void log(@NotNull String message) {
                    // 请求或者响应开始
                    if (message.startsWith("--> POST") || message.startsWith("--> GET")) {
                        mMessage.setLength(0);
                    }
                    // 以{}或者[] 形式的说明是响应结果的json数据，需要进行格式化
                    if ((message.startsWith("{") && message.endsWith("}"))
                            || (message.startsWith("[") && message.endsWith("]"))) {
                        message = LogUtil.formatJson(message);

                    }
                    mMessage.append(message.concat("\n"));
                    // 请求或者响应结束，打印整条日志
                    if (message.startsWith("<-- END HTTP")) {
                        LogUtil.d(mMessage.toString());
                    }
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY);

    // 配置全局公共请求头
//    private static final Interceptor headerInterceptor = chain -> {
//        AccountService accountService = YehApp.getInstance().accountService();
//        Request.Builder builder = chain.request().newBuilder()
//                .addHeader("access-token", accountService.token()) // token
//                .addHeader("language-id", accountService.language() + "") // 语言
//                .addHeader("currency-code", accountService.currency()) // 货币
//                .addHeader("device-type", "android") // 平台
//                .removeHeader("User-Agent")//移除旧的 BuildConfig.VERSION_NAME
//                .addHeader("User-Agent", "Yehwang/Android:" + BuildConfig.VERSION_NAME);
//
//        if (Constants.ApiPreview) {
//            builder.addHeader("X-RUN-ENV", "preview"); //预发环境
//        } else {
//            builder.removeHeader("X-RUN-ENV");
//        }
//        return chain.proceed(builder.build());
//    };

    /*
     * URL重定向的方式 切换 baseurl
     */
    private static final Interceptor mUrlInterceptor = chain -> {
        Request request = chain.request();
        String url = request.url().toString();
        if (Constants.ApiTest) {
            if (url.startsWith(Constants.ROOTURL_OFFICIAL)) {
                return chain.proceed(request.newBuilder()
                        .url(url.replaceFirst(Constants.ROOTURL_OFFICIAL, Constants.ROOTURL_TEST)).build());
            }

        } else {
            if (url.startsWith(Constants.ROOTURL_TEST)) {
                return chain.proceed(request.newBuilder()
                        .url(url.replaceFirst(Constants.ROOTURL_TEST, Constants.ROOTURL_OFFICIAL)).build());
            }
        }

        return chain.proceed(request);
    };

    // 网络缓存
    private static final Interceptor cacheInterceptor = chain -> {
        Response response = chain.proceed(chain.request());
        if (NetworkTools.isConnected()) {
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", /*"public, only-if-cached, max-stale=0"*/"max-age=" + 60 * 60 * 24 * 180) //有网时 时效为0 即不缓存
                    .build();
        } else {
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "max-age=" + 60 * 60 * 24 * 180) //无网时 时效设为一周
                    .build();
        }

    };

    // 网络缓存
    private static final Interceptor cacheControlInterceptor = chain -> {
        Request request = chain.request();

        if (!NetworkTools.isConnected()) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response originalResponse = chain.proceed(request);
        if (NetworkTools.isConnected()) {
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", /*"public, only-if-cached, max-stale=0"*/"public, only-if-cached, max-stale=" + 60 * 60 * 24 * 180) //有网时 时效为0 即不缓存
                    .build();
        } else {
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 180) //无网时 时效设为一周
                    .build();
        }
    };
}
